# coding: utf-8
# @Author: cyl
# @File: 06进阶1.py
# @Time: 2024/07/08 20:04:18
class A:
    a = 1
    b = 2
    c = 3


"""1. 使用__slots__"""
class B:
    __slots__ = ("d", "e", "f")


a: A = A()
b:B = B()

a.d = 4
a.e = 5
print(a.d)
print(a.e)

print(b.__dir__)
# b.g = 100
# b.h = 200
# print(b.g) # AttributeError: 'B' object has no attribute 'g'


"""is =="""
# is是判断两边id是否相等
# ==是判断两边值是否相等
# a: int = ""
# abc: list = []
# with open("xxx.txt", mode="r") as f:
#     abc.append("xxx")
# for i in abc:
#     a += i
# if a is None:
#     print("xxx")
# if a == "":
#     print("xxx")

a = [1, 2, 3]
b = [1, 2, 3]
print(id(a), id(b))
print(a == b) # true
print(a is b) # false

# python内部的优化机制
# 对于小量的int str等值, python会将这些值的id指向同一个id
a = 1
b = 1
# 或者
a = "abc"
b = "abc"
print(a == b) # true
print(id(a), id(b))
print(a is b) # true

# 单例
class Person:
    def __new__(cls, *args, **kwargs):
        if not hasattr(cls, '_instance'):
            cls._instance = super(Person, cls).__new__(cls, *args, **kwargs)
        return cls._instance


person1: Person = Person()
person2: Person = Person()
print(id(person1), id(person2))
print(person1 is person2)
print(person1 == person2)


# 1. isinstance判断会寻找类或者属性的"链"所属关系, 如果在"链"中仍然返回True
# 2. type只会根据指定的判断类型进行判断, 不会寻找"链"关系
class A:
    pass
   
class B(A):
    pass

b = B()
print(isinstance(b, B))   # True
print(isinstance(b, A))   # True
print(type(b) is B)   # True
print(type(b) is A)   # False


"""+ += extend"""
# + ：开辟一个新的列表空间, 产生一个新的内存地址, 后面只能为list
a = [1, 2]
c = a + [3, 4]
print(c) # [1, 2, 3, 4]

# += : 在原有的列表上拓展空间, 且可以为任意的序列类型
a = [1, 2]
a += [3, 4]
print(a) # [1, 2, 3, 4]

a = [1, 2]
a += (3, 4)
print(a) # [1, 2, 3, 4]

a = [1, 2]
a += range(3)
print(a) # [1, 2, 0, 1, 2]

a = [1, 2]
a += "123"
print(a) # [1, 2, '1', '2', '3']

# extend: 与+=类似, extend内部就是通过遍历传进来的列表后, 在原有的列表上进行append
a = [1, 2]
a.extend(range(3))
print(a) # [1, 2, 0, 1, 2]

a = [1, 2]
a.append([3, 4])
print(a) # [1, 2, [3, 4]]
